package com.bysj.lms.controller;


import com.bysj.lms.common.ResultModel;
import com.bysj.lms.pojo.entity.DictionaryItem;
import com.bysj.lms.service.IDictionaryItemService;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaojiakai
 * @since 2022-02-04
 */
@Api(tags = "数据字典")
@RestController
@RequestMapping("/dictionary-item")
public class DictionaryItemController {

    @Autowired
    IDictionaryItemService dictionaryItemService;


    @ApiOperation(value = "分页查询数据字典")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页"),
            @ApiImplicitParam(name = "count",value = "页的大小"),
            @ApiImplicitParam(name = "type",value = "字典类型id")
    })
    @GetMapping("/findPage")
    public ResultModel find(Integer page, Integer count, Integer typeId){
        PageInfo pageInfo = dictionaryItemService.findByPage(typeId, page, count);
        return ResultModel.success("查询成功",pageInfo);
    }

    @ApiOperation(value = "根据type名查询字典数据")
    @GetMapping("/findByType")
    public ResultModel findByType(String type){
        List<DictionaryItem> list = dictionaryItemService.findByType(type);
        return ResultModel.success("查询成功",list);
    }

    @ApiOperation(value = "添加字典数据")
    @PostMapping("/add")
    public ResultModel add(@RequestBody DictionaryItem dictionaryItem){
        DictionaryItem one = dictionaryItemService.find(dictionaryItem.getTypeId(), dictionaryItem.getName());
        if(one == null){
            boolean save = dictionaryItemService.save(dictionaryItem);
            if(!save) return ResultModel.failure("添加失败");
        }else if (StringUtils.equals(one.getStatus(),"1")){
            boolean b = dictionaryItemService.updateStatus(dictionaryItem.getId(), 0);
            if(!b) return ResultModel.failure("添加失败");
        }
        return ResultModel.success("添加成功");
    }

    @PutMapping("/update")
    @ApiOperation(value = "根据id更新")
    public ResultModel update(@RequestBody DictionaryItem dictionaryItem){
        boolean update = dictionaryItemService.updateById(dictionaryItem);
        if(update){
            return ResultModel.success("修改成功");
        }
        return ResultModel.failure("修改失败");
    }

    @DeleteMapping("/delete")
    @ApiOperation(value = "根据id删除")
    public ResultModel delete(Integer id){
        boolean b = dictionaryItemService.updateStatus(id, 1);
        if(b){
            return ResultModel.success("删除成功");
        }
        return ResultModel.failure("删除失败");
    }
}

